package com.hngy.xpq.android_practice.http.map;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.hngy.xpq.android_practice.R;
import com.hngy.xpq.android_practice.http.TcpClient;
import com.hngy.xpq.android_practice.ui.home.User_Comm;

import java.util.ArrayList;

public class BaiDuMap extends AppCompatActivity{

    private boolean isPermissionRequested = false;

    private MapView mMapView = null;
    private BaiduMap baiduMap = null ,mBaiduMap = null;
    private LocationClient locationClient;

    private boolean isFirstLoc = true;

    SharedPreferences comm;

    public void addOpt() {
        LatLng point = new LatLng(39.915119, 116.403963);
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.tab);
        OverlayOptions options = new MarkerOptions().position(point).icon(bitmap);
        baiduMap.addOverlay(options);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bai_du_map);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        baiduMap = mMapView.getMap();

        mBaiduMap = mMapView.getMap();
        requestPermission();


        locationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(5000);
        locationClient.setLocOption(option);
        locationClient.registerLocationListener(new MyLocationListener());
        locationClient.start();

        //从服务器获得商家位置信息
        comm = super.getSharedPreferences("comm",MODE_PRIVATE);
        String information = "DW001//" + comm.getString("name","");
        String a = new TcpClient().Transits(information);

        if (!a.equals("商家未开启定位")) {
            String[] position = a.split("\\,");
            //显示商家位置和信息
            LatLng llText = new LatLng(Double.valueOf(position[0]), Double.valueOf(position[1]));
            //构建TextOptions对象
            OverlayOptions mTextOptions = new TextOptions()
                    .text(comm.getString("name","")) //文字内容
                    .bgColor(0xAAFFFF00) //背景色
                    .fontSize(24) //字号
                    .fontColor(0xFFFF00FF) //文字颜色
                    .rotate(0) //旋转角度
                    .position(llText);
            //在地图上显示文字覆盖物
            Overlay mText = mBaiduMap.addOverlay(mTextOptions);

            //定义Maker坐标点
            LatLng point = new LatLng(Double.valueOf(position[0]), Double.valueOf(position[1]));
            //构建Marker图标
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.tab);
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions options = new MarkerOptions()
                    .position(point)
                    .icon(bitmap);
            //在地图上添加Marker，并显示
            mBaiduMap.addOverlay(options);
        } else {
            IndexToast("商家未开启定位");
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || baiduMap == null) {
                return;
            }
            baiduMap.setMyLocationEnabled(true);
            MyLocationData data = new MyLocationData.Builder()
                    .latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude())
                    .direction(bdLocation.getDirection())
                    .accuracy(bdLocation.getRadius())
                    .build();
            baiduMap.setMyLocationData(data);

            if (isFirstLoc) {
                isFirstLoc = false;
                float f = baiduMap.getMaxZoomLevel();
                LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, f-4);
                baiduMap.animateMapStatus(u);

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    @Override
    protected void onDestroy() {
        locationClient.stop();
        baiduMap.setMyLocationEnabled(false);
        super.onDestroy();
        mMapView.onDestroy();
    }



    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested) {
            isPermissionRequested = true;
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
            };

            for (String perm : permissions) {
                    if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(BaiDuMap.this, perm)) {
                    permissionsList.add(perm);
                    // 进入到这里代表没有权限.
                }
            }

            if (!permissionsList.isEmpty()) {
                String[] strings = new String[permissionsList.size()];
                ActivityCompat.requestPermissions(BaiDuMap.this,permissionsList.toArray(strings), 0);
            }
        }
    }

    public void IndexToast(String text){
        Toast.makeText(BaiDuMap.this,text,Toast.LENGTH_SHORT).show();
    }
}